﻿using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Core.Message.Entities;
using Core.ExceptionHandling;
using Core.Controls.Message;
using vHCS.HR.Business;
using vHCS.HR.Entities;
using vHCS.LS.Business;
using Telerik.Web.UI;
using Core.Common.Session;
using Core.NTier.Entities;
using System.IO;
using System.Configuration;
using Core.Controls.DataReader;
using vHCS.K2App.Shared;

namespace vHCS.K2App.MdlK2
{
    public partial class HR_AddNewMultiRotationHR : Core.NTier.UserInterface.BaseFormNotPer
    {
        #region Const
        private const string _TargetFolder = "UploadFile/WorkingRecord";
        #endregion

        #region Properties
        /// <summary>
        /// Get function id của chức năng
        /// </summary>
        public long FunctionID
        {
            get
            {
                
                //Lấy tên form hiện tại đang được mở
                string fuction = Request.ServerVariables["URL"].Substring(Request.ServerVariables["URL"].LastIndexOf("/") + 1);
                //Lấy đường dẫn từ tên form được config trong web.config
                string Path = ConfigurationManager.AppSettings.Get(fuction);
                //Nếu đường dẫn !=""
                if (!string.IsNullOrEmpty(Path))
                {
                    vHCS.SYS.Business.SYS_FunctionsCollection cl = new vHCS.SYS.Business.SYS_FunctionsCollection();
                    vHCS.SYS.Business.SYS_FunctionsBL bl = new vHCS.SYS.Business.SYS_FunctionsBL();
                    //trả về thông tin function theo đường dẫn truyền vào (dựa vào field Virtual Path trong table SYS_tblFunction)
                    bl = cl.ReturnTitleFunctionByPath(Path);
                    if (bl.DTO != null)
                    {
                        return bl.FunctionId;
                    }
                }

                return 0;
            }
        }
        #endregion

        private static RadAjaxManager ajax = new RadAjaxManager();
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    
                    LoadGrid(false);
                    ClientScript.RegisterStartupScript(Page.GetType(), "LoadMaximize", "LoadMaximize();", true);
                }
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }

        protected void dtgWorkingRecord_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
        {
            try
            {
                //RadAjaxManager ajax = new RadAjaxManager();
                //ajax = RadAjaxManager.GetCurrent(Page);
                HR_WorkingRecordCollection cl = new HR_WorkingRecordCollection();
                if (e.Item is GridDataItem)
                {
                    GridDataItem item = (GridDataItem)e.Item;
                    RadComboBox cboLoaihinhthuthaydoi = (RadComboBox)item.FindControl("cboLoaiHinhThuc");
                    RadComboBox cbohinhthucthaydoi = (RadComboBox)item.FindControl("cboHinhthucthaydoi");
                    RadComboBox cbococautochuc = (RadComboBox)item.FindControl("cboOrgChart");
                    TextBox txtLeader = (TextBox)item.FindControl("txtLeader");
                    //Lấy combo prochart
                    RadComboBox cboProChart = (RadComboBox)item.FindControl("cboProChart");
                    RadComboBox cboProRanking = (RadComboBox)item.FindControl("cboProRanking");
                    RadComboBox cboProGrade = (RadComboBox)item.FindControl("cboProGrade");
                    //Lấy combo mgtchart
                    RadComboBox cboMgtChart = (RadComboBox)item.FindControl("cboMgtChart");
                    RadComboBox cboMgtRanking = (RadComboBox)item.FindControl("cboMgtRaking");
                    RadComboBox cboMgtGrade = (RadComboBox)item.FindControl("cboMgtGrade");

                    //Lấy combo cap bac
                    RadComboBox cboCapbac = (RadComboBox)item.FindControl("cboCapbac");
                    //Lấy combo Jobtitle
                    RadComboBox cboJobTitle = (RadComboBox)item.FindControl("cboChucvu");
                    CoreDataSource dtsJobtitle = (CoreDataSource)item.FindControl("dtsJobTitle");
                    //Lấy textbox Emptype
                    TextBox txtEmptype = (TextBox)item.FindControl("txtLoaiNhanVien");
                    //Lấy texbox Emptypeid
                    TextBox txtEmptypeid = (TextBox)item.FindControl("txtLoaiNhanVienID");
                    //Lấy combo jobrole
                    RadComboBox cboJobRole = (RadComboBox)item.FindControl("cboJobRole");
                    TextBox txtJobRole = (TextBox)item.FindControl("txtJobRoleID");
                    //Lấy combo văn phòng làm việc
                    RadComboBox cboVanphonglamviec = (RadComboBox)item.FindControl("cboVanphonglamviec");
                    //Lấy textbox lương gross
                    RadNumericTextBox txtLuongGross = (RadNumericTextBox)item.FindControl("txtGross");
                    //Lấy textbox lương căn bản
                    RadNumericTextBox txtLuongcanban = (RadNumericTextBox)item.FindControl("txtLuongcanban");
                    //Lấy textbox lương KPI
                    RadNumericTextBox txtLuongKPI = (RadNumericTextBox)item.FindControl("txtKPI");
                    //Lấy textbox trợ cấp tổng hợp
                    RadNumericTextBox txtTrocapTH = (RadNumericTextBox)item.FindControl("txtTrocaptonghop");
                    RadComboBox cboNguoibaocao = (RadComboBox)item.FindControl("cboReportTo");
                    RadComboBox txtNguoipheduyet = (RadComboBox)item.FindControl("cboNguoiPheDuyet");
                    RadComboBox txtNguoiMentor = (RadComboBox)item.FindControl("cboNguoiMentor");
                    CoreDataSource dtsReportTo = (CoreDataSource)item.FindControl("dtsReportTo");
                    CoreDataSource dtsApprover = (CoreDataSource)item.FindControl("dtsApprover");
                    CoreDataSource dtsMentor = (CoreDataSource)item.FindControl("dtsMentor");

                    Panel pnlProChart = (Panel)item.FindControl("pnlProChart");
                    Panel pnlMgtChart = (Panel)item.FindControl("pnlMgtChart");

                    //Gán dữ liệu ban đầu cho các control thêm mới

                    long hierachyid = 0;
                    long.TryParse(item["HierarchyId"].Text.Trim(), out hierachyid);
                    long workingrecordid = 0;
                    long.TryParse(item["WorkingRecordID"].Text.Trim(), out workingrecordid);

                    //Gán cây cơ cấu tổ chức
                    string orchartname = cl.SelectOrgChartName(workingrecordid);
                    cbococautochuc.Items.Clear();
                    RadComboBoxItem item_orgchart = new RadComboBoxItem(orchartname, hierachyid.ToString());
                    cbococautochuc.Items.Insert(0, item_orgchart);
                    cbococautochuc.SelectedIndex = 0;

                    //Gán chức vụ cho nhân viên
                    dtsJobtitle.SelectParameters["prefix"].DefaultValue = "$SelectedValue$" + item["JobTitleID"].Text.Trim();
                    cboJobTitle.DataSourceID = dtsJobtitle.ID;
                    cboJobTitle.DataBind();
                    SetComboValue(cboJobTitle, item["JobTitleID"].Text.Trim());

                    //Gán cây cơ cấu chuyên môn
                    string prochartname = cl.SelectProJobName(workingrecordid);
                    cboProChart.Items.Clear();
                    RadComboBoxItem item_prochart = new RadComboBoxItem(prochartname, cl.SelectProJobID(workingrecordid));
                    cboProChart.Items.Insert(0, item_prochart);
                    cboProChart.SelectedIndex = 0;
                    //ProRanking
                    SetComboValue(cboProRanking, item["ProRankingId"].Text.Trim(), true);


                    //Gán cây cơ cấu quản lý
                    string mgtchartname = cl.SelectMgtJobName(workingrecordid);
                    cboMgtChart.Items.Clear();
                    RadComboBoxItem item_mgtchart = new RadComboBoxItem(mgtchartname, cl.SelectMgtJobID(workingrecordid));
                    cboMgtChart.Items.Insert(0, item_mgtchart);
                    cboMgtChart.SelectedIndex = 0;
                    //MgtRanking
                    SetComboValue(cboMgtRanking, item["MgtRankingId"].Text.Trim(), true);

                    //Set dữ liệu cho ProGrade và MgtGrade
                    PopulateProGrade(item, cboProGrade, cboProRanking, item["ProGradeId"].Text.Trim());
                    PopulateMgtGrade(item, cboMgtGrade, cboMgtRanking, item["MgtGradeId"].Text.Trim());
                    //ProGrade
                    SetComboValue(cboProGrade, item["ProGradeId"].Text.Trim(), true);
                    //MgtGrade
                    SetComboValue(cboMgtGrade, item["MgtGradeId"].Text.Trim(), true);
                    //Gán loại nhân viên
                    txtEmptype.Text = item["EmpTypeName"].Text.Trim().Replace("&nbsp;", "");
                    txtEmptypeid.Text = item["LSEmpTypeID"].Text.Trim().Replace("&nbsp;", "");

                    //Load dữ liệu cây jobchart và joblevel theo JobTitle
                    long jobtitle = 0;
                    long.TryParse(cboJobTitle.SelectedValue, out jobtitle);
                    if (jobtitle > 0)
                        PopulateJobTitle(Convert.ToInt64(cboJobTitle.SelectedValue), cboProChart, cboMgtChart, cboCapbac,
                            item["ProSubGroupId"].Text.Trim().Replace("&nbsp;", ""), item["MgtSubGroupId"].Text.Trim().Replace("&nbsp;", ""), item["LSLevelID"].Text.Trim().Replace("&nbsp;", ""));

                    //Gán cấp bậc cho nhân viên
                    SetComboValue(cboCapbac, item["LSLevelID"].Text.Trim(), true);
                    //PopulateJobTitle(cboCapbac, cboMgtChart, cboProChart, cboJobTitle);

                    //Gán JobRole
                    string jobroleid = cl.SelectJobRoleID(workingrecordid);
                    txtJobRole.Text = jobroleid.Trim();
                    LoadJobRole(jobroleid, cboJobRole);
                    //Load thông tin ban đầu cho combobox
                    string jobrolename = cl.SelectJobRoleName(workingrecordid);
                    RadComboBoxItem item_jobrole = new RadComboBoxItem(jobrolename, jobroleid);
                    cboJobRole.Items.Insert(cboJobRole.Items.Count, item_jobrole);
                    cboJobRole.SelectedIndex = cboJobRole.Items.Count - 1;
                    cboJobRole.Items[cboJobRole.Items.Count - 1].Visible = false;

                    //Gán văn phòng làm việc
                    SetComboValue(cboVanphonglamviec, item["LSWorkPlaceID"].Text.Trim());
                    //Gán leader
                    txtLeader.Text = item["Leader"].Text.Trim().Replace("&nbsp;", "");

                    //Gan luong Gross
                    txtLuongGross.Value = item["GrossSalary"].Text.Trim().Replace("&nbsp;", "") == "" ? 0 : Convert.ToDouble(item["GrossSalary"].Text.Trim());
                    //Gán lương căn bản
                    txtLuongcanban.Value = item["BasisSalary"].Text.Trim().Replace("&nbsp;", "") == "" ? 0 : Convert.ToDouble(item["BasisSalary"].Text.Trim());
                    txtLuongKPI.Value = item["KPI"].Text.Trim().Replace("&nbsp;", "") == "" ? 0 : Convert.ToDouble(item["KPI"].Text.Trim());
                    txtTrocapTH.Value = item["GeneralSusidies"].Text.Trim().Replace("&nbsp;", "") == "" ? 0 : Convert.ToDouble(item["GeneralSusidies"].Text.Trim());

                    //Gán người báo cáo, phê duyệt, mentor
                    dtsReportTo.SelectParameters["prefix"].DefaultValue = "$SelectedValue$" + item["ReportingLine"].Text.Trim().Replace("&nbsp;", "");
                    cboNguoibaocao.DataSourceID = dtsReportTo.ID;
                    cboNguoibaocao.DataBind();
                    SetComboValue(cboNguoibaocao, item["ReportingLine"].Text.Trim().Replace("&nbsp;", ""));

                    dtsApprover.SelectParameters["prefix"].DefaultValue = "$SelectedValue$" + item["Approver"].Text.Trim().Replace("&nbsp;", "");
                    txtNguoipheduyet.DataSourceID = dtsApprover.ID;
                    txtNguoipheduyet.DataBind();
                    SetComboValue(txtNguoipheduyet, item["Approver"].Text.Trim().Replace("&nbsp;", ""));

                    dtsMentor.SelectParameters["prefix"].DefaultValue = "$SelectedValue$" + item["Mentor"].Text.Trim().Replace("&nbsp;", "");
                    txtNguoiMentor.DataSourceID = dtsMentor.ID;
                    txtNguoiMentor.DataBind();
                    SetComboValue(txtNguoiMentor, item["Mentor"].Text.Trim().Replace("&nbsp;", ""));

                    //Gán phân quyền dữ liệu
                    if (item["DataModify"].Text.Replace("&nbsp;", "").Trim() != "")
                    {
                        bool datamodify = Convert.ToBoolean(item["DataModify"].Text.Replace("&nbsp;", "").Trim());

                        CheckBox chkmodify = (CheckBox)item["ClientSelectColumn"].Controls[0];
                        chkmodify.Visible = datamodify;
                    }

                    RadTreeView treeviewpro = (RadTreeView)cboProChart.Items[0].FindControl("trvProChart");
                    RadTreeView treeviewmgt = (RadTreeView)cboMgtChart.Items[0].FindControl("trvMgtChart");
                    //Gán ajax cho các control trên lưới
                    SetAjaxControl(cboLoaihinhthuthaydoi, cbohinhthucthaydoi);
                    SetAjaxControl(cbococautochuc, txtLeader);
                    //SetAjaxControl(cboProChart, cboJobTitle);
                    //SetAjaxControl(cboMgtChart, cboJobTitle);
                    //SetAjaxControl(cboCapbac, cboJobTitle);
                    SetAjaxControl(cboCapbac, txtEmptype);
                    SetAjaxControl(cboCapbac, txtEmptypeid);
                    //SetAjaxControl(cboJobTitle, cboProChart);
                    //SetAjaxControl(cboJobTitle, cboMgtChart);
                    SetAjaxControl(cboJobTitle, cboCapbac);
                    //SetAjaxControl(cboJobTitle, treeviewmgt);
                    //SetAjaxControl(cboJobTitle, treeviewpro);
                    SetAjaxControl(cboJobTitle, pnlProChart);
                    SetAjaxControl(cboJobTitle, pnlMgtChart);
                }
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }

        #region Function
        /// <summary>
        /// DungN2
        /// Load dữ liệu lên lưới
        /// </summary>
        public void LoadGrid(bool view)
        {
            try
            {
                HR_WorkingRecordCollection cl = new HR_WorkingRecordCollection();
                dtgWorkingRecord.DataSource = cl.SelectMultiWR(HR_ctrlUserSearch1.ItemData, view,FunctionID);
                dtgWorkingRecord.DataBind();
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }

        public void SetAjaxGrid()
        {
            try
            {
                foreach (GridDataItem item in dtgWorkingRecord.Items)
                {
                    RadComboBox cboLoaihinhthuthaydoi = (RadComboBox)item.FindControl("cboLoaiHinhThuc");
                    RadComboBox cbohinhthucthaydoi = (RadComboBox)item.FindControl("cboHinhthucthaydoi");
                    RadComboBox cbococautochuc = (RadComboBox)item.FindControl("cboOrgChart");
                    TextBox txtLeader = (TextBox)item.FindControl("txtLeader");
                    //RadComboBox cboProChart = (RadComboBox)item.FindControl("cboProChart");
                    ////Lấy combo mgtchart
                    //RadComboBox cboMgtChart = (RadComboBox)item.FindControl("cboMgtChart");
                    ////Lấy combo cap bac
                    RadComboBox cboCapbac = (RadComboBox)item.FindControl("cboCapbac");
                    //Lấy combo Jobtitle
                    RadComboBox cboJobTitle = (RadComboBox)item.FindControl("cboChucvu");
                    //Lấy textbox Emptype
                    TextBox txtEmptype = (TextBox)item.FindControl("txtLoaiNhanVien");
                    //Lấy texbox Emptypeid
                    TextBox txtEmptypeid = (TextBox)item.FindControl("txtLoaiNhanVienID");
                    //RadTreeView treeviewpro = (RadTreeView)cboProChart.Items[0].FindControl("trvProChart");
                    //RadTreeView treeviewmgt = (RadTreeView)cboMgtChart.Items[0].FindControl("trvMgtChart");
                    Panel pnlProChart = (Panel)item.FindControl("pnlProChart");
                    Panel pnlMgtChart = (Panel)item.FindControl("pnlMgtChart");
                    RadComboBox cboProRanking = (RadComboBox)item.FindControl("cboProRanking");
                    RadComboBox cboMgtRanking = (RadComboBox)item.FindControl("cboMgtRaking");

                    //Gán ajax cho các control trên lưới
                    SetAjaxControl(cboLoaihinhthuthaydoi, cbohinhthucthaydoi);
                    SetAjaxControl(cbococautochuc, txtLeader);
                    SetAjaxControl(cboCapbac, txtEmptype);
                    SetAjaxControl(cboCapbac, txtEmptypeid);
                    SetAjaxControl(cboJobTitle, cboCapbac);
                    SetAjaxControl(cboJobTitle, pnlProChart);
                    SetAjaxControl(cboJobTitle, pnlMgtChart);
                    SetAjaxControl(cboProRanking, pnlProChart);
                    SetAjaxControl(cboMgtRanking, pnlMgtChart);
                }
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }

        /// <summary>
        /// DungN2
        /// Gán ajax cho các control trên lưới
        /// </summary>
        public void SetAjaxControl(Control ctrl1, Control ctrl2)
        {
            try
            {
                ajax = RadAjaxManager.GetCurrent(Page);

                ajax.AjaxSettings.AddAjaxSetting(ctrl1, ctrl2, RadAjaxLoadingPanel1);
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }

        /// <summary>
        /// Load danh sách cho cboJobTitle
        /// </summary>
        protected void PopulateJobTitle(RadComboBox cboCapbac, RadComboBox cboMgtChart, RadComboBox cboProChart, RadComboBox cboChucvu)
        {
            try
            {
                long jobLevelId = 0;
                HIE_JobChartNode selectedNode = new HIE_JobChartNode();
                long.TryParse(cboCapbac.SelectedValue, out jobLevelId);

                //Nếu cơ cấu quản lý không có giá trị thì chọn cơ cấu chuyên môn
                if (string.IsNullOrEmpty(cboMgtChart.SelectedValue)
                    || cboMgtChart.SelectedValue == HIE_HierarchyCollection.JobChartNullNodeValue)
                    selectedNode = HIE_HierarchyCollection.ParseJobChartNode(cboProChart.SelectedValue);
                else
                    selectedNode = HIE_HierarchyCollection.ParseJobChartNode(cboMgtChart.SelectedValue);

                //Gán chức vụ vào combo
                LS_JobTitleCollection cl = new LS_JobTitleCollection();
                cboChucvu.DataSource = cl.GetComboItems(jobLevelId, selectedNode.JobFamilyId, selectedNode.JobGroupId, selectedNode.SubGroupId, "", true, false);
                cboChucvu.DataTextField = "Name";
                cboChucvu.DataValueField = "ID";
                cboChucvu.DataBind();
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }

        /// <summary>
        /// DungN2
        /// Get combo jobchart và cấp bậc theo jobtitle
        /// </summary>
        /// <param name="jobtitle">mã jobtitle</param>
        /// <param name="joblevel">mã joblevel, được sử dụng khi edit mẫu tin</param>
        public void PopulateJobTitle(long jobtitle, RadComboBox cboProChart, RadComboBox cboMgtChart, RadComboBox cboCapbac, string ProSubGroupId, string MgtSubGroupId, string JobLevelId)
        {
            try
            {
                GridDataItem item = (GridDataItem)cboProChart.NamingContainer;

                //Load lại combo prochart
                Core.Controls.DataReader.CoreDataSource dtsProChart = (Core.Controls.DataReader.CoreDataSource)item.FindControl("dtsProChart");
                dtsProChart.SelectParameters["Jobtitle"].DefaultValue = jobtitle.ToString();
                dtsProChart.SelectParameters["prefix"].DefaultValue = "$SelectedValue$" + ProSubGroupId;
                RadTreeView treeviewpro = (RadTreeView)cboProChart.Items[0].FindControl("trvProChart");
                treeviewpro.DataSourceID = dtsProChart.ID;
                treeviewpro.DataBind();

                //Load lại combo mgtchart
                Core.Controls.DataReader.CoreDataSource dtsMgtChart = (Core.Controls.DataReader.CoreDataSource)item.FindControl("dtsMgtChart");
                dtsMgtChart.SelectParameters["Jobtitle"].DefaultValue = jobtitle.ToString();
                dtsMgtChart.SelectParameters["prefix"].DefaultValue = "$SelectedValue$" + MgtSubGroupId;
                RadTreeView treeviewmgt = (RadTreeView)cboMgtChart.Items[0].FindControl("trvMgtChart");
                treeviewmgt.DataSourceID = dtsMgtChart.ID;
                treeviewmgt.DataBind();


                //Load lại combo cấp bậc
                Core.Controls.DataReader.CoreDataSource dtsJobLevel = (Core.Controls.DataReader.CoreDataSource)item.FindControl("dtsJobLevel");
                dtsJobLevel.SelectParameters["jobtitle"].DefaultValue = jobtitle.ToString();
                dtsJobLevel.SelectParameters["p_strPrefix"].DefaultValue = "$SelectedValue$" + JobLevelId;
                cboCapbac.DataSourceID = dtsJobLevel.ID;
                cboCapbac.DataBind();

                SetAjaxGrid();
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }

        /// <summary>
        /// Dungn2
        /// Get combo ProGrade và MgtGrade theo ProRanking và MgtRanking
        /// </summary>
        /// <param name="item">item trên lưới đang hiện hành</param>
        /// <param name="cboPrograde">combo ProGrade</param>
        /// <param name="cboMgtgrade">combo MgtGrade</param>
        /// <param name="cboProRanking">combo ProRanking</param>
        /// <param name="cboMgtRanking">combo MgtRanking</param>
        /// <param name="ProGradeId">Mã ProGrade đang được chọn</param>
        /// <param name="MgtGradeId">Mã MgtGrade đang được chọn</param>
        public void PopulateProGrade(GridDataItem item, RadComboBox cboPrograde, RadComboBox cboProRanking, string ProGradeId)
        {
            try
            {
                Core.Controls.DataReader.CoreDataSource dtsProGrade = (Core.Controls.DataReader.CoreDataSource)item.FindControl("dtsProGrade");
                dtsProGrade.SelectParameters["prefix"].DefaultValue = "$SelectedValue$" + ProGradeId;
                dtsProGrade.SelectParameters["rankingid"].DefaultValue = cboProRanking.SelectedValue;
                cboPrograde.DataSourceID = dtsProGrade.ID;
                cboPrograde.DataBind();
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }

        public void PopulateMgtGrade(GridDataItem item, RadComboBox cboMgtgrade, RadComboBox cboMgtRanking, string MgtGradeId)
        {
            try
            {
                Core.Controls.DataReader.CoreDataSource dtsMgtGrade = (Core.Controls.DataReader.CoreDataSource)item.FindControl("dtsMgtGrade");
                dtsMgtGrade.SelectParameters["prefix"].DefaultValue = "$SelectedValue$" + MgtGradeId;
                dtsMgtGrade.SelectParameters["rankingid"].DefaultValue = cboMgtRanking.SelectedValue;
                cboMgtgrade.DataSourceID = dtsMgtGrade.ID;
                cboMgtgrade.DataBind();
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }

        public void SetStatusChange(object sender)
        {
            try
            {
                LS_ChangeFormCollection cl = new LS_ChangeFormCollection();
                //Get combo loại hình thức trên lưới
                RadComboBox cboloaihinhthuc = (RadComboBox)sender;
                //Get combo hình thức trên lưới
                GridDataItem item = (GridDataItem)cboloaihinhthuc.NamingContainer;
                RadComboBox cbohinhthuc = (RadComboBox)item.FindControl("cboHinhthucthaydoi");

                //Load dữ liệu combo hình thức theo loại hình thức được chọn
                cbohinhthuc.DataSource = cl.GetComboItemsByType(Convert.ToInt64(cboloaihinhthuc.SelectedValue == "" ? "0" : cboloaihinhthuc.SelectedValue), "", true, false);
                cbohinhthuc.DataTextField = "Name";
                cbohinhthuc.DataValueField = "ID";
                cbohinhthuc.DataBind();

                //Gán ajax cho các control trên lưới
                SetAjaxGrid();
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }

        /// <summary>
        /// DungN2
        /// </summary>
        /// <param name="arrayjobrole">Mảng jobrole</param>
        /// <param name="cboJobRole">Combo JobRole</param>
        public void LoadJobRole(string arrayjobrole, RadComboBox cboJobRole)
        {
            try
            {
                string[] str_list = arrayjobrole.Split(';');
                foreach (string str_jobrole in str_list)
                {
                    long jobrole = 0;
                    long.TryParse(str_jobrole, out jobrole);
                    if (jobrole > 0)
                    {
                        cboJobRole.SelectedValue = jobrole.ToString();
                        RadComboBoxItem item = cboJobRole.SelectedItem;
                        CheckBox chk = (CheckBox)item.FindControl("chkJobRole");
                        if (chk != null)
                            chk.Checked = true;
                    }
                }

                SetComboValue(cboJobRole, null, true);
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }

        /// <summary>
        /// Convert DS JobFamily,JobGroup,SoupGroup
        /// </summary>
        /// <param name="listid"></param>
        /// <returns></returns>
        public List<Int64> ParseJob(string listid)
        {
            List<Int64> result = new List<Int64>();
            try
            {
                string[] str_listid = listid.Split(';');
                foreach (string id in str_listid)
                {
                    result.Add(Convert.ToInt64(string.IsNullOrEmpty(id)?"0":id));
                }

            }
            catch (Exception ex)
            {
                DataAccessExceptionHandler.HandleException(ex);
            }
            return result;
        }

        public void InsertJobRole(RadComboBox cboJobRole, long workingrecordid)
        {
            try
            {
                HR_WorkingRecordCollection cl = new HR_WorkingRecordCollection();
                List<long> listjobrole = new List<long>();

                foreach (RadComboBoxItem item in cboJobRole.Items)
                {
                    CheckBox chk = (CheckBox)item.FindControl("chkJobRole");
                    if (chk.Checked)
                    {
                        listjobrole.Add(Convert.ToInt64(item.Value));
                    }
                }

                if (listjobrole.Count > 0)
                {
                    cl.Delete_JobRole(workingrecordid);
                    cl.InsertJobRole(workingrecordid, listjobrole);
                }

            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }

        #region Tạo đường dẫn đến file
        /// <summary>
        /// Author: DungN2, create date: 28/02/2011
        /// Tạo đường dẫn đến file
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="extension"></param>
        /// <param name="counter"></param>
        /// <returns></returns>
        public string ReturnPath(string filename, string extension, int counter)
        {
            string path = "";
            try
            {
                if (counter <= 0)
                {
                    path = Server.MapPath("../" + _TargetFolder + "/" + filename + extension);
                }
                else
                {
                    path = Server.MapPath("../" + _TargetFolder + "/" + filename + counter.ToString() + extension);
                }
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
            return path;
        }
        #endregion

        #region Phương thức Upload File
        /// <summary>
        /// Author: DungN2, create date: 28/02/2011
        /// Phương thức Upload File
        /// </summary>
        public string UploadFile(RadAsyncUpload uplAttatchFile)
        {
            string filename = "";
            try
            {
                foreach (UploadedFile uploadfile in uplAttatchFile.UploadedFiles)
                {
                    int counter = 0;
                    filename = uploadfile.GetName();
                    string path = ReturnPath(uploadfile.GetNameWithoutExtension(), uploadfile.GetExtension(), 0);
                    while (File.Exists(path))//Kiểm tra file có tồn tại chưa nếu tồn tại thì thêm số thứ tự file vào tên file
                    {
                        counter++;
                        path = ReturnPath(uploadfile.GetNameWithoutExtension(), uploadfile.GetExtension(), counter);
                        filename = uploadfile.GetNameWithoutExtension() + counter.ToString() + uploadfile.GetExtension();
                    }

                    uploadfile.SaveAs(path);
                }
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
            return filename;
        }
        #endregion

        /// <summary>
        /// Kiểm tra dữ liệu bắt buộc nhập
        /// </summary>
        /// <returns>false:Không hợp lệ; true:hợp lệ</returns>
        public bool CheckRequireValid()
        {
            bool check = true;
            hdfListEmp.Value = "";
            try
            {
                foreach (GridDataItem item in dtgWorkingRecord.SelectedItems)
                {
                    //Get các control cần lấy giá trị
                    RadComboBox cbohinhthucthaydoi = (RadComboBox)item.FindControl("cboHinhthucthaydoi");
                    RadComboBox cbococautochuc = (RadComboBox)item.FindControl("cboOrgChart");
                    RadDatePicker dpkNgayhieuluc = (RadDatePicker)item.FindControl("dpkNgayhieuluc");
                    //Lấy combo prochart
                    RadComboBox cboProChart = (RadComboBox)item.FindControl("cboProChart");
                    //Lấy combo mgtchart
                    RadComboBox cboMgtChart = (RadComboBox)item.FindControl("cboMgtChart");
                    //Lấy combo cap bac
                    RadComboBox cboCapbac = (RadComboBox)item.FindControl("cboCapbac");
                    //Lấy combo Jobtitle
                    RadComboBox cboJobTitle = (RadComboBox)item.FindControl("cboChucvu");
                    //Lấy combo jobrole
                    RadComboBox cboJobRole = (RadComboBox)item.FindControl("cboJobRole");
                    //Lấy combo văn phòng làm việc
                    RadComboBox cboVanphonglamviec = (RadComboBox)item.FindControl("cboVanphonglamviec");

                    if (string.IsNullOrEmpty(cbohinhthucthaydoi.SelectedValue))
                        check = false;
                    if (string.IsNullOrEmpty(cbococautochuc.SelectedValue))
                        check = false;
                    if (dpkNgayhieuluc.SelectedDate.HasValue == false || Convert.ToDateTime(dpkNgayhieuluc.SelectedDate).Year == 1)
                        check = false;
                    if (string.IsNullOrEmpty(cboProChart.SelectedValue))
                        check = false;
                    if (string.IsNullOrEmpty(cboMgtChart.SelectedValue))
                        check = false;
                    if (string.IsNullOrEmpty(cboCapbac.SelectedValue))
                        check = false;
                    if (string.IsNullOrEmpty(cboJobTitle.SelectedValue))
                        check = false;
                    if (string.IsNullOrEmpty(cboVanphonglamviec.SelectedValue))
                        check = false;

                    if (check == false)
                        hdfListEmp.Value += ", " + item["FullName"].Text.Trim();
                }
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
            return check;
        }

        /// <summary>
        /// Lấy mã JobRole từ combo JobRole
        /// true: hợp lệ; false: không hợp lệ
        /// </summary>
        /// <returns></returns>
        public bool CheckIDJobRole(TextBox txtJobRole, RadComboBox cboJobRole)
        {
            try
            {
                string jobroleold = ";" + txtJobRole.Text + ";";
                foreach (RadComboBoxItem item in cboJobRole.Items)
                {
                    CheckBox chk = (CheckBox)item.FindControl("chkJobRole");
                    if (chk.Checked)
                    {
                        if (jobroleold.Contains(";" + item.Value + ";") == false)
                            return true;
                    }
                }
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
            return false;
        }

        /// <summary>
        /// DungN2
        /// Kiểm tra nơi đến có trùng với nơi đi, nếu trùng trả về false
        /// </summary>
        /// <returns></returns>
        public bool CheckNoiDen()
        {
            try
            {
                hdfListEmp.Value = "";
                foreach (GridDataItem item in dtgWorkingRecord.SelectedItems)
                {
                    RadComboBox cbococautochuc = (RadComboBox)item.FindControl("cboOrgChart");
                    //Lấy combo prochart
                    RadComboBox cboProChart = (RadComboBox)item.FindControl("cboProChart");
                    //Lấy combo mgtchart
                    RadComboBox cboMgtChart = (RadComboBox)item.FindControl("cboMgtChart");
                    //Lấy combo ProRaking
                    RadComboBox cboProRaking = (RadComboBox)item.FindControl("cboProRanking");
                    //Lấy combo ProGrade
                    RadComboBox cboProGrade = (RadComboBox)item.FindControl("cboProGrade");
                    //Lấy combo cap bac
                    RadComboBox cboCapbac = (RadComboBox)item.FindControl("cboCapbac");
                    //Lấy combo Jobtitle
                    RadComboBox cboJobTitle = (RadComboBox)item.FindControl("cboChucvu");
                    //Lấy combo jobrole
                    RadComboBox cboJobRole = (RadComboBox)item.FindControl("cboJobRole");
                    TextBox txtJobRole = (TextBox)item.FindControl("txtJobRoleID");
                    //Lấy combo văn phòng làm việc
                    RadComboBox cboVanphonglamviec = (RadComboBox)item.FindControl("cboVanphonglamviec");

                    HR_WorkingRecordBL bl_last = new HR_WorkingRecordBL();
                    HR_WorkingRecordCollection cl = new HR_WorkingRecordCollection();
                    bl_last = cl.SelectLastWRByEmpID_ForFormWR(Convert.ToInt64(item["EmpID"].Text.Trim()));

                    //Lấy dữ liệu nơi đi
                    long id = bl_last.WorkingRecordID;
                    long workplace = bl_last.LSWorkPlaceID;
                    long hierachy = bl_last.HierarchyId;
                    string proid = bl_last.ProJobFamilyId + ";" + bl_last.ProJobGroupId + ";" + bl_last.ProSubGroupId;
                    string mgtid = bl_last.MgtJobFamilyId + ";" + bl_last.MgtJobGroupId + ";" + bl_last.MgtSubGroupId;
                    long level = bl_last.LSLevelID;
                    long jobtitle = bl_last.JobTitleID;
                    long proranking = bl_last.ProRankingId;
                    long prograde = bl_last.ProGradeId;

                    //Lấy dữ liệu nơi đến
                    long workplace_now = 0;
                    long.TryParse(cboVanphonglamviec.SelectedValue, out workplace_now);

                    long hierachy_now = 0;
                    long.TryParse(cbococautochuc.SelectedValue, out hierachy_now);

                    string proid_now = cboProChart.SelectedValue;
                    string mgtid_now = cboMgtChart.SelectedValue;

                    long proranking_now = 0;
                    long.TryParse(cboProRaking.SelectedValue, out proranking_now);
                    long prograde_now = 0;
                    long.TryParse(cboProGrade.SelectedValue, out prograde_now);

                    long level_now = 0;
                    long.TryParse(cboCapbac.SelectedValue, out level_now);

                    long jobtitle_now = 0;
                    long.TryParse(cboJobTitle.SelectedValue, out jobtitle_now);

                    if (workplace == workplace_now)
                        if (hierachy == hierachy_now)
                            if (proid == proid_now)
                                if (level == level_now)
                                    if (jobtitle == jobtitle_now)
                                        if (prograde == prograde_now)
                                            if (proranking == proranking_now)
                                                hdfListEmp.Value += ", " + item["FullName"].Text.Trim();
                }
                if (hdfListEmp.Value != "")
                    return false;
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
            return true;
        }

        /// <summary>
        /// DungN2
        /// Kiểm tra ngày hiệu lực phải lớn hơn hoặc bằng ngày vào công ty
        /// </summary>
        /// <returns>true: hợp lệ; false: không hợp lệ</returns>
        public bool CheckNgayvaocty()
        {
            bool check = true;
            hdfListEmp.Value = "";
            try
            {
                foreach (GridDataItem item in dtgWorkingRecord.SelectedItems)
                {
                    RadDatePicker dpkNgayhieuluc = (RadDatePicker)item.FindControl("dpkNgayhieuluc");

                    HR_EmpBL bl = new HR_EmpBL();
                    HR_EmpCollection cl = new HR_EmpCollection();
                    bl = cl.SelectByID(Convert.ToInt64(item["EmpID"].Text.Trim()));

                    if (bl.DTO != null)
                    {
                        if (Convert.ToDateTime(dpkNgayhieuluc.SelectedDate).Date < bl.JoinDate)
                            check = false;
                    }

                    if (check == false)
                        hdfListEmp.Value += ", " + item["FullName"].Text.Trim();
                }
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
            return check;
        }

        #endregion

        protected void btnTimKiem_Click(object sender, EventArgs e)
        {
            LoadGrid(true);
        }

        protected void cboChangeType_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            SetStatusChange(sender);
        }

        protected void trvOrgChart_NodeClick(object sender, RadTreeNodeEventArgs e)
        {
            try
            {
                RadTreeView treeview = (RadTreeView)sender;
                //Get combo orgchart
                RadComboBox combo = (RadComboBox)treeview.NamingContainer.NamingContainer;

                GridDataItem item = (GridDataItem)combo.NamingContainer;

                RadComboBox cboorchart = (RadComboBox)item.FindControl("cboOrgChart");
                TextBox txtleader = (TextBox)item.FindControl("txtLeader");

                HR_WorkingRecordCollection cl = new HR_WorkingRecordCollection();
                txtleader.Text = cl.ReturnLeader(Convert.ToInt64(cboorchart.SelectedValue == "" ? "0" : cboorchart.SelectedValue));
                SetAjaxGrid();
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }

        protected void trvOrgChart_OnDataBound(object sender, EventArgs e)
        {
            try
            {
                //Gán ajax cho control treeview orgchart in combo
                RadTreeView treeview = (RadTreeView)sender;
                RadComboBox combo = (RadComboBox)treeview.NamingContainer.NamingContainer;
                GridDataItem item = (GridDataItem)combo.NamingContainer;

                TextBox txtleader = (TextBox)item.FindControl("txtLeader");
                //SetAjaxControl(treeview, txtleader);
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }

        protected void cboCapbac_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            try
            {

                //Lấy combo cap bac
                RadComboBox cboCapbac = (RadComboBox)sender;
                //Lấy dòng dữ liệu trên grid đang thao tác
                GridDataItem item = (GridDataItem)cboCapbac.NamingContainer;
                //Lấy textbox Emptype
                TextBox txtEmptype = (TextBox)item.FindControl("txtLoaiNhanVien");
                //Lấy texbox Emptypeid
                TextBox txtEmptypeid = (TextBox)item.FindControl("txtLoaiNhanVienID");

                //Load loại nhân viên theo cấp bậc
                LS_JobLevelBL joblevel_bl = new LS_JobLevelBL();
                LS_JobLevelCollection joblevel_cl = new LS_JobLevelCollection();
                joblevel_bl = joblevel_cl.SelectByID(Convert.ToInt64(cboCapbac.SelectedValue == "" ? "0" : cboCapbac.SelectedValue));

                if (joblevel_bl.DTO != null)
                {
                    LS_EmpTypeBL emptype_bl = new LS_EmpTypeBL();
                    LS_EmpTypeCollection emptype_cl = new LS_EmpTypeCollection();
                    emptype_bl = emptype_cl.SelectByID(joblevel_bl.LSEmpTypeID);

                    if (emptype_bl.DTO != null)
                    {
                        txtEmptype.Text = (SessionManager.LanguageID == "VN" || string.IsNullOrEmpty(emptype_bl.NameEN)) ? emptype_bl.NameVN : emptype_bl.NameEN;
                        txtEmptypeid.Text = emptype_bl.LSEmpTypeID.ToString();
                    }
                    else
                    {
                        txtEmptype.Text = null;
                        txtEmptypeid.Text = null;
                    }
                }
                else
                {
                    txtEmptype.Text = null;
                    txtEmptypeid.Text = null;
                }

                SetAjaxGrid();
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }

        protected void cboChucvu_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            try
            {
                RadComboBox cboChucvu = (RadComboBox)sender;
                GridDataItem item = (GridDataItem)cboChucvu.NamingContainer;
                RadComboBox cboProChart = (RadComboBox)item.FindControl("cboProChart");
                RadComboBox cboMgtChart = (RadComboBox)item.FindControl("cboMgtChart");
                RadComboBox cboJobLevel = (RadComboBox)item.FindControl("cboCapbac");
                TextBox txtLoaiNhanVien = (TextBox)item.FindControl("txtLoaiNhanVien");
                TextBox txtLoaiNhanVienID = (TextBox)item.FindControl("txtLoaiNhanVienID");
                long jobtitle = 0;
                long.TryParse(cboChucvu.SelectedValue, out jobtitle);
                if (jobtitle > 0)
                {
                    cboProChart.Items.Clear();
                    cboProChart.Items.Insert(0, new RadComboBoxItem());
                    cboProChart.SelectedIndex = 0;

                    cboMgtChart.Items.Clear();
                    cboMgtChart.Items.Insert(0, new RadComboBoxItem());
                    cboMgtChart.SelectedIndex = 0;

                    //Kiểm tra mapping giữa Jobtitle và SubGroup (ProChart)
                    //Nếu tồn tại 1 mapping giữa Jobtitle và SubGroup thì gán vào ProChart
                    HR_WorkingRecordCollection cl = new HR_WorkingRecordCollection();
                    long subgroupid = cl.CheckJobTitle_SubGroup(jobtitle);
                    if (subgroupid > 0)
                    {
                        string prochartname = cl.GetProChartName(subgroupid);
                        string prochartid = cl.GetProChartID(subgroupid);

                        cboProChart.Items.Clear();
                        cboProChart.Items.Insert(0, new RadComboBoxItem(prochartname, prochartid));
                        cboProChart.SelectedIndex = 0;

                        PopulateJobTitle(jobtitle, cboProChart, cboMgtChart, cboJobLevel, "", "", "");
                        //rttProChart_input.Text = prochartname;
                    }

                    LS_JobTitleBL bl_tt = new LS_JobTitleBL();
                    LS_JobTitleCollection cl_tt = new LS_JobTitleCollection();
                    bl_tt = cl_tt.SelectByID(jobtitle);
                    if (bl_tt.DTO != null)
                    {
                        cboJobLevel.DataBind();
                        SetComboValue(cboJobLevel, bl_tt.LevelId.ToString());
                        //Load loại nhân viên theo cấp bậc
                        LS_JobLevelBL joblevel_bl = new LS_JobLevelBL();
                        LS_JobLevelCollection joblevel_cl = new LS_JobLevelCollection();
                        joblevel_bl = joblevel_cl.SelectByID(bl_tt.LevelId);

                        if (joblevel_bl.DTO != null)
                        {
                            LS_EmpTypeBL emptype_bl = new LS_EmpTypeBL();
                            LS_EmpTypeCollection emptype_cl = new LS_EmpTypeCollection();
                            emptype_bl = emptype_cl.SelectByID(joblevel_bl.LSEmpTypeID);

                            if (emptype_bl.DTO != null)
                            {
                                txtLoaiNhanVien.Text = (SessionManager.LanguageID == "VN" || string.IsNullOrEmpty(emptype_bl.NameEN)) ? emptype_bl.NameVN : emptype_bl.NameEN;
                                txtLoaiNhanVienID.Text = emptype_bl.LSEmpTypeID.ToString();
                            }
                            else
                            {
                                txtLoaiNhanVien.Text = null;
                                txtLoaiNhanVienID.Text = null;
                            }
                        }
                        else
                        {
                            txtLoaiNhanVien.Text = null;
                            txtLoaiNhanVienID.Text = null;
                        }
                    }
                }

                SetAjaxGrid();
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }

        protected void cboProRanking_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            try
            {
                RadComboBox cboProRanking = (RadComboBox)sender;
                GridDataItem item = (GridDataItem)cboProRanking.NamingContainer;
                RadComboBox cboProGrade = (RadComboBox)item.FindControl("cboProGrade");
                PopulateProGrade(item, cboProGrade, cboProRanking, "");

                SetAjaxGrid();
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }

        protected void cboMgtRaking_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            try
            {
                RadComboBox cboMgtRanking = (RadComboBox)sender;
                GridDataItem item = (GridDataItem)cboMgtRanking.NamingContainer;
                RadComboBox cboMgtGrade = (RadComboBox)item.FindControl("cboMgtGrade");
                PopulateMgtGrade(item, cboMgtGrade, cboMgtRanking, "");

                SetAjaxGrid();
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }

        protected void btnRefresh_Click(object sender, EventArgs e)
        {
            try
            {
                HR_ctrlUserSearch1.ResetForm();
                LoadGrid(false);
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }

        protected void btnSubmit_Top_Click(object sender, EventArgs e)
        {
            try
            {
                if (CheckNgayvaocty())//Kiểm tra ngày hiệu lực phải lớn hơn hoặc bằng ngày vào công ty
                {
                    foreach (GridDataItem item in dtgWorkingRecord.SelectedItems)
                    {
                        CheckBox chkmodify = (CheckBox)item["ClientSelectColumn"].Controls[0];
                        if (chkmodify.Visible)
                        {
                            long WorkingRecordId=0;
                            HR_WorkingRecordBL bl = new HR_WorkingRecordBL();
                            HR_WorkingRecordCollection cl = new HR_WorkingRecordCollection();

                            //Get các control cần lấy giá trị để lưu xuống
                            RadComboBox cboLoaihinhthuthaydoi = (RadComboBox)item.FindControl("cboLoaiHinhThuc");
                            RadComboBox cbohinhthucthaydoi = (RadComboBox)item.FindControl("cboHinhthucthaydoi");
                            RadComboBox cbococautochuc = (RadComboBox)item.FindControl("cboOrgChart");
                            RadDatePicker dpkNgayhieuluc = (RadDatePicker)item.FindControl("dpkNgayhieuluc");
                            TextBox txtLeader = (TextBox)item.FindControl("txtLeader");
                            //Lấy combo prochart
                            RadComboBox cboProChart = (RadComboBox)item.FindControl("cboProChart");
                            RadComboBox cboProRanking = (RadComboBox)item.FindControl("cboProRanking");
                            RadComboBox cboProGrade = (RadComboBox)item.FindControl("cboProGrade");
                            //Lấy combo mgtchart
                            RadComboBox cboMgtChart = (RadComboBox)item.FindControl("cboMgtChart");
                            RadComboBox cboMgtRanking = (RadComboBox)item.FindControl("cboMgtRaking");
                            RadComboBox cboMgtGrade = (RadComboBox)item.FindControl("cboMgtGrade");
                            //Lấy combo cap bac
                            RadComboBox cboCapbac = (RadComboBox)item.FindControl("cboCapbac");
                            //Lấy combo Jobtitle
                            RadComboBox cboJobTitle = (RadComboBox)item.FindControl("cboChucvu");
                            //Lấy textbox Emptype
                            TextBox txtEmptype = (TextBox)item.FindControl("txtLoaiNhanVien");
                            //Lấy texbox Emptypeid
                            TextBox txtEmptypeid = (TextBox)item.FindControl("txtLoaiNhanVienID");
                            //Lấy combo jobrole
                            RadComboBox cboJobRole = (RadComboBox)item.FindControl("cboJobRole");
                            //Lấy combo văn phòng làm việc
                            RadComboBox cboVanphonglamviec = (RadComboBox)item.FindControl("cboVanphonglamviec");
                            //Lấy textbox lương gross
                            RadNumericTextBox txtLuongGross = (RadNumericTextBox)item.FindControl("txtGross");
                            //Lấy textbox lương căn bản
                            RadNumericTextBox txtLuongcanban = (RadNumericTextBox)item.FindControl("txtLuongcanban");
                            //Lấy textbox lương KPI
                            RadNumericTextBox txtLuongKPI = (RadNumericTextBox)item.FindControl("txtKPI");
                            //Lấy textbox trợ cấp tổng hợp
                            RadNumericTextBox txtTrocapTH = (RadNumericTextBox)item.FindControl("txtTrocaptonghop");
                            //Lấy checkbox thay đổi lương
                            CheckBox chkThaydoiluong = (CheckBox)item.FindControl("chkChangeSalary");
                            //Lấy combo người báo cáo
                            RadComboBox cboReportTo = (RadComboBox)item.FindControl("cboReportTo");
                            RadComboBox txtNguoiPheduyet = (RadComboBox)item.FindControl("cboNguoiPheDuyet");
                            RadComboBox txtNguoiMentor = (RadComboBox)item.FindControl("cboNguoiMentor");
                            CheckBox chkDuytri = (CheckBox)item.FindControl("chkDuytriquyenhan");
                            RadAsyncUpload uplUpload = (RadAsyncUpload)item.FindControl("uplFileUpload");
                            CheckBox chkQuyetdinh = (CheckBox)item.FindControl("chkquyedinh");
                            string UserName = item["UserName"].Text.Trim();

                            //Gán giá trị từ các control 
                            long workingrecordid = 0;
                            long.TryParse(item["WorkingRecordID"].Text.Trim(), out workingrecordid);

                            bl.LSStatusChangeID = Convert.ToInt64(cbohinhthucthaydoi.SelectedValue == "" ? "0" : cbohinhthucthaydoi.SelectedValue);
                            bl.FromDate = Convert.ToDateTime(dpkNgayhieuluc.SelectedDate);
                            bl.HierarchyId = Convert.ToInt64(cbococautochuc.SelectedValue == "" ? "0" : cbococautochuc.SelectedValue);
                            //Projob
                            List<Int64> Projob = ParseJob(cboProChart.SelectedValue);
                            bl.ProJobFamilyId = Projob[0];
                            bl.ProJobGroupId = Projob[1];
                            bl.ProSubGroupId = Projob[2];
                            bl.ProRankingId = Convert.ToInt64(cboProRanking.SelectedValue == "" ? "0" : cboProRanking.SelectedValue);
                            bl.ProGradeId = Convert.ToInt64(cboProGrade.SelectedValue == "" ? "0" : cboProGrade.SelectedValue);
                            //MgtJob
                            if (!string.IsNullOrEmpty(cboMgtChart.SelectedValue))
                            {
                                List<Int64> MgtJob = ParseJob(cboMgtChart.SelectedValue);
                                bl.MgtJobFamilyId = MgtJob[0];
                                bl.MgtJobGroupId = MgtJob[1];
                                bl.MgtSubGroupId = MgtJob[2];
                                bl.MgtRankingId = Convert.ToInt64(cboMgtRanking.SelectedValue == "" ? "0" : cboMgtRanking.SelectedValue);
                                bl.MgtGradeId = Convert.ToInt64(cboMgtGrade.SelectedValue == "" ? "0" : cboMgtGrade.SelectedValue);
                            }
                            //Gán loại nhân viên
                            bl.LSEmpTypeID = Convert.ToInt64(txtEmptypeid.Text.Trim() == "" ? "0" : txtEmptypeid.Text.Trim());
                            //Gán cấp bậc
                            bl.LSLevelID = Convert.ToInt64(cboCapbac.SelectedValue == "" ? "0" : cboCapbac.SelectedValue);
                            //Gan chuc vu
                            bl.JobTitleID = Convert.ToInt64(cboJobTitle.SelectedValue == "" ? "0" : cboJobTitle.SelectedValue);
                            //Gán văn phòng làm việc
                            bl.LSWorkPlaceID = Convert.ToInt64(cboVanphonglamviec.SelectedValue == "" ? "0" : cboVanphonglamviec.SelectedValue);
                            //Gán leader
                            bl.Leader = txtLeader.Text.Trim();
                            //Gán combo người báo cáo
                            bl.ReportingLine = cboReportTo.SelectedValue;
                            bl.Approver = txtNguoiPheduyet.SelectedValue;
                            bl.Mentor = txtNguoiMentor.SelectedValue;
                            bl.IsRemainRight = chkDuytri.Checked;
                            bl.IsChangeSalary = chkThaydoiluong.Checked;
                            bl.GrossSalary = Convert.ToDouble(txtLuongGross.Value);
                            bl.BasisSalary = Convert.ToDouble(txtLuongcanban.Value);
                            bl.KPI = Convert.ToDouble(txtLuongKPI.Value);
                            bl.GeneralSusidies = Convert.ToDouble(txtTrocapTH.Value);
                            bl.AttachFile = UploadFile(uplUpload);
                            bl.Status = false;
                            bl.IsWorkingRecord = 0;
                            bl.CreatedUser = SessionManager.Username;
                            bl.Decision = chkQuyetdinh.Checked;
                            bl.EmpID = Convert.ToInt64(item["EmpID"].Text.Trim());

                            HR_WorkingRecordBL bl_check = new HR_WorkingRecordBL();
                            bl_check = cl.SelectByEffectivedate(bl.EmpID, bl.FromDate, 0, 0);
                            if (bl_check.DTO == null)
                            {
                                WorkingRecordId=cl.Insert(bl);
                                InsertJobRole(cboJobRole, workingrecordid);
                            }
                            else
                            {
                                BusinessLogicCustomException ex = new BusinessLogicCustomException("12480");
                                ex.AdditionInfo = new String[] { item["FullName"].Text.Trim(), bl_check.FromDate.ToShortDateString() };
                                throw ex;
                            }

                            //Start K2
                            K2Collection colK2 = new K2Collection();
                            HIE_EmpInHierarchyCollection cl_emphie = new HIE_EmpInHierarchyCollection();
                            string empid = bl.EmpID.ToString();
                            //Lấy trưởng phòng ban nơi đi
                            string fromhierarchy = cl_emphie.SelectDeptHie(Convert.ToInt64(string.IsNullOrEmpty(item["HierarchyId"].Text.Trim()) ? "0" : item["HierarchyId"].Text.Trim())).ToString();
                            //Lấy trưởng phòng ban nơi đến
                            string tohierarchy = cl_emphie.SelectDeptHie(Convert.ToInt64(string.IsNullOrEmpty(cbococautochuc.SelectedValue) ? "0" : cbococautochuc.SelectedValue)).ToString();
                            //Lấy node nơi đến
                            string hierarchyid = cbococautochuc.SelectedValue;
                            string NextApproved = colK2.GetLeaderOfHierarchy(Convert.ToInt16(string.IsNullOrEmpty(fromhierarchy) ? "0" : fromhierarchy));

                            #region Lấy thông tin gửi mail next approve
                            vHCS.SYS.Business.SYS_MailTemplateCollection cl_nextapprove = new vHCS.SYS.Business.SYS_MailTemplateCollection();
                            vHCS.SYS.Business.SYS_MailTemplateBL bl_nextapprove = new vHCS.SYS.Business.SYS_MailTemplateBL();
                            vHCS.SYS.Business.SYS_MailTemplateBL bl_signature = new vHCS.SYS.Business.SYS_MailTemplateBL();
                            bl_nextapprove = cl_nextapprove.FindByCode("WR_NextApprove");
                            bl_signature = cl_nextapprove.FindByCode("SIGNATURE");
                            string MailContent_NextApprove = "";
                            string MailSubject_NextApprove = "";

                            if (bl_nextapprove.DTO != null)
                            {
                                MailContent_NextApprove = bl_nextapprove.ContentVN.Replace("$Creator$", SessionManager.UserDomain);
                                MailContent_NextApprove = MailContent_NextApprove.Replace("$url$", ConfigurationManager.AppSettings.Get("LinkWRApprove_Old"));
                                MailContent_NextApprove += bl_signature.ContentVN;
                                MailSubject_NextApprove = bl_nextapprove.TitleVN.Replace("$Creator$", SessionManager.UserDomain);
                            }

                            //Lấy email người gửi đến
                            vHCS.SYS.Business.SYS_UsersCollection cl_user = new vHCS.SYS.Business.SYS_UsersCollection();
                            vHCS.SYS.Business.SYS_UsersBL bl_user = new vHCS.SYS.Business.SYS_UsersBL();
                            bl_user = cl_user.FindById_BL(NextApproved);
                            string email_nextapprove = "";
                            if (bl_user.DTO != null)
                            {
                                email_nextapprove = bl_user.Email;
                            }
                            #endregion

                            #region Lấy thông tin gửi mail request
                            vHCS.SYS.Business.SYS_MailTemplateBL bl_request = new SYS.Business.SYS_MailTemplateBL();
                            bl_request = cl_nextapprove.FindByCode("WR_Request");
                            string MailContent_Request = "";
                            string MailSubject_Request = "";
                            string Email_Request = "";
                            if (bl_request.DTO != null)
                            {
                                MailContent_Request = bl_request.ContentVN.Replace("$RequestDate$", DateTime.Now.ToShortDateString()).Replace("$Approver$", NextApproved);
                                MailContent_Request = MailContent_Request.Replace("$url$", ConfigurationManager.AppSettings.Get("LinkStaffMovement") + WorkingRecordId.ToString());
                                MailContent_Request += bl_signature.ContentVN;
                                MailSubject_Request = bl_request.TitleVN;
                            }

                            bl_user = cl_user.FindById_BL(SessionManager.UserDomain);
                            if (bl_user.DTO != null)
                            {
                                Email_Request = bl_user.Email;
                            }
                            #endregion

                            #region Lấy thông tin gửi mail cho HR/HRP khi creator submitted
                            vHCS.SYS.Business.SYS_MailTemplateBL bl_hr = new SYS.Business.SYS_MailTemplateBL();
                            bl_hr = cl_nextapprove.FindByCode("WR_CreatorToHR");
                            string MailContent_HR = "";
                            string MailSubject_HR = "";
                            string Email_HR = "";
                            string Email_HRP = "";
                            if (bl_hr.DTO != null)
                            {
                                string EmpCode = item["EmpCode"].ToString();
                                string FullName = item["FullName"].ToString();
                                string cJobTitle = item["JobTitleName"].ToString();
                                string cJobLevel = item["JobLevelName"].ToString();
                                //Lấy thông tin phòng ban
                                string cdept = "";
                                string ndept = "";
                                string njobtitle = "";
                                string njoblevel = "";
                                HIE_HierarchyCollection cl_hie = new HIE_HierarchyCollection();
                                HIE_HierarchyBL bl_hie = new HIE_HierarchyBL();
                                //Lấy thông tin phòng ban cũ
                                bl_hie = cl_hie.SelectByID(Convert.ToInt64(fromhierarchy));
                                if (bl_hie.DTO != null)
                                    cdept = bl_hie.NameVN;
                                //Lấy thông tin phòng ban mới
                                bl_hie = cl_hie.SelectByID(Convert.ToInt64(tohierarchy));
                                if (bl_hie.DTO != null)
                                    ndept = bl_hie.NameVN;
                                //End Lấy thông tin phòng ban

                                //Lấy thông tin chức vụ mới

                                LS_JobTitleBL bl_jobtitle = new LS_JobTitleBL();
                                LS_JobTitleCollection cl_jobtitle = new LS_JobTitleCollection();
                                LS_JobLevelBL bl_joblevel = new LS_JobLevelBL();
                                LS_JobLevelCollection cl_joblevel = new LS_JobLevelCollection();
                                bl_jobtitle = cl_jobtitle.SelectByID(Convert.ToInt64(cboJobTitle.SelectedValue));
                                if (bl_jobtitle.DTO != null)
                                    njobtitle = bl_jobtitle.NameVN;
                                bl_joblevel = cl_joblevel.SelectByID(Convert.ToInt64(cboCapbac.SelectedValue));
                                if (bl_joblevel.DTO != null)
                                    njoblevel = bl_joblevel.NameVN;

                                //Lấy hình thức thay đôi
                                string changeform = "";
                                LS_ChangeFormBL bl_changeform = new LS_ChangeFormBL();
                                LS_ChangeFormCollection cl_changeform = new LS_ChangeFormCollection();
                                bl_changeform = cl_changeform.SelectByID(Convert.ToInt64(cbohinhthucthaydoi.SelectedValue));
                                if (bl_changeform.DTO != null)
                                    changeform = bl_changeform.NameVN;

                                MailContent_HR = bl_hr.ContentVN;
                                //Gán Employee code vào content
                                MailContent_HR = MailContent_HR.Replace("$EmployeeCode$", EmpCode);
                                //Gán FullName vào content
                                MailContent_HR = MailContent_HR.Replace("$FullName$", FullName);
                                //Gán current jobtitle
                                MailContent_HR = MailContent_HR.Replace("$cJobTitle$", cJobTitle);
                                //Gán current joblevel
                                MailContent_HR = MailContent_HR.Replace("$cJobLevel$", cJobLevel);
                                //Gán current dept
                                MailContent_HR = MailContent_HR.Replace("$cDept$", cdept);
                                //Gán new jobtitle
                                MailContent_HR = MailContent_HR.Replace("$nJobTitle$", njobtitle);
                                //Gán new joblevel
                                MailContent_HR = MailContent_HR.Replace("$nJobLevel$", njoblevel);
                                //Gán new dept
                                MailContent_HR = MailContent_HR.Replace("$nDept$", ndept);
                                //Gán hình thức thay đổi
                                MailContent_HR = MailContent_HR.Replace("$Type$", changeform);

                                //Gán signature
                                MailContent_HR += bl_signature.ContentVN;
                                //Gán Subject
                                MailSubject_HR = bl_hr.TitleVN;
                                //Gán phòng ban vào subject
                                MailSubject_HR = MailSubject_HR.Replace("$Dept$", cdept);
                                MailSubject_HR = MailSubject_HR.Replace("$Creator$", SessionManager.UserDomain);
                            }

                            //Gán email HR
                            bl_user = cl_user.FindById_BL(colK2.GetUserOfHR());
                            if (bl_user.DTO != null)
                                Email_HR = bl_user.Email;

                            //Gán email HRP
                            string HRP = colK2.GetUserOfHRP(bl.EmpID);
                            bl_user = cl_user.FindById_BL(HRP);
                            if (bl_user.DTO != null)
                                Email_HRP = bl_user.Email;

                            // Add user CC
                            List<string> listUserCC = new List<string>();
                            listUserCC.Add(HRP);
                            #endregion

                            //End
                            if (NextApproved != "")
                            {

                                string ApproveLink = ConfigurationManager.AppSettings.Get("LinkWRApprove");
                                string ViewHistoryLink = ConfigurationManager.AppSettings.Get("LinkStaffMovement") + workingrecordid.ToString();
                                //Get thông tin Expire
                                string ExpireDay = ConfigurationManager.AppSettings.Get("SM_ExpireDay");
                                string ExpireAlert = ConfigurationManager.AppSettings.Get("SM_ExpireAlert");

                                int iTypeID = K2CoreLib.K2Utils.GetTypeIDProcessFromEfrom("HR_WorkingRecord");
                                string sLinkContent = ConfigurationManager.AppSettings.Get("History_WR") + WorkingRecordId.ToString(); 
                                string status = "0"; //(0: In process, 1: Complete, 2: Rework, 3:Reject)
                                string eformid = K2CoreLib.K2Utils.submit2EForm(SessionManager.UserDomain, SessionManager.UserDomain, iTypeID, DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"), sLinkContent, status, UserName);
                                string[] lst_eformid = eformid.Split(',');

                                int proid = K2CoreLib.K2Utils.StartWordkingProcess(empid, WorkingRecordId.ToString(), fromhierarchy, tohierarchy, hierarchyid,
                                                                                    NextApproved, MailContent_NextApprove, MailSubject_NextApprove, email_nextapprove,
                                                                                    MailContent_Request, MailSubject_Request, Email_Request, MailSubject_HR, MailContent_HR, Email_HR, Email_HRP, SessionManager.UserDomain, lst_eformid[1], lst_eformid[0],"", item["UserName"].Text.Trim()
                                                                                    ,ApproveLink,ViewHistoryLink,ExpireDay,ExpireAlert);

                                K2CoreLib.K2Utils.Update2EForm("0", lst_eformid[1], proid.ToString());
                                cl.UpdateEform(Convert.ToInt64(WorkingRecordId.ToString()), lst_eformid[1]);

                                #region begin to save history
                                HR_WorkingRecordCollection cl_wr = new HR_WorkingRecordCollection();
                                cl_wr.InsertHistory(Convert.ToInt64(WorkingRecordId.ToString()), DateTime.Now, SessionManager.UserDomain, "Requester", "Request", "",1,0);

                                //Insert CC (Reviewer) comment
                                HistoryComment his = new HistoryComment();
                                his.InsertReviewerComment(Convert.ToInt64(WorkingRecordId.ToString()), listUserCC, 1);
                                #endregion End save
                            }


                        }
                    }
                    ClientScript.RegisterStartupScript(Page.GetType(), "ClosePage", "ClosePage();", true);
                    HR_ctrlUserSearch1.ResetForm();
                    LoadGrid(false);
                }
                else
                {
                    SetAjaxGrid();
                    BusinessLogicCustomException ex = new BusinessLogicCustomException("12250");
                    ex.AdditionInfo = new String[] { hdfListEmp.Value.Trim(',') };
                    throw ex;
                }
                SetAjaxGrid();
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }
    }
}